// stores/user.js
import { defineStore } from 'pinia'
import api from '@/api'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token'),
    name: '',
    avatar: '',
    roles: []
  }),

  getters: {
    hasToken: (state) => !!state.token
  },

  actions: {
    // 登录方法
    async login(userInfo) {
      const res = await api.user.login(userInfo)
      console.log(res, '登录成功')
      this.token = res.data.token
      localStorage.setItem('token', res.data.token)

      const infoRes = await api.user.getInfo()
      this.name = infoRes.data.name
      this.avatar = infoRes.data.avatar
      this.roles = infoRes.data.roles

      // 修改跳转逻辑
      const redirectPath = router.currentRoute.value.query.redirect
      if (this.roles.some(role => ['admin', 'editor'].includes(role))) {
        router.push(redirectPath || '/dashboard')
      } else {
        router.push(redirectPath || '/front') // 普通用户默认跳转前台
      }
      
      return Promise.resolve(res)
    },

    // 登出方法
    async logout() {
      await logout()
      this.$reset()
      localStorage.removeItem('token')
      router.push('/login')
    },

    $reset() { // 自定义重置方法
      this.token = ''
      this.name = ''
      this.avatar = ''
      this.roles = []
    }
  },

  // 开启持久化（需要安装插件 pinia-plugin-persistedstate）
  persist: {
    paths: ['token']
  }
})
